<?php
require ('constants.php');
function check_input($data){
  $data = trim($data);
  $data = htmlspecialchars($data);
  return $data;
}

function redirect_to($url){
  header("Location: {$url}");
  exit;
}

function confirm_query($result_set) {
  if (!$result_set) {
    die("Database query failed: " . mysql_error());
  }
}
	
function redirect_to_base($fromtype){
   
  redirect_to(get_base_link($fromtype));
}

function get_base_link($fromtype){
  $logintype = isloggedin();
  if($fromtype != "public"){
    $loc = "../";
  }
  else
    $loc = "";

  $publiclocation = $loc . "index.php?at=1";
  $memberlocation = $loc . "member/member.php";
  $tellerlocation = $loc . "teller/teller.php";
  $adminlocation = $loc . "admin/administrator_home.php";
   
  if($logintype == "member")
    return $memberlocation;
  else if($logintype == "teller")
    return $tellerlocation;
  else if($logintype == "admin")
    return $adminlocation;
  else
    return $publiclocation;
}

function ensure_logged_in($login_type=""){
  
  if(!isset($_SESSION['logged_in']) && $login_type == "public"){ //not logged in and on a public page, do nothing
  }
  else if (!isset($_SESSION["logged_in"]) && $login_type != "public"){ //not logged in and on a non-public page - go to index.php
    redirect_to("../index.php?at=1");
  }
  else if($_SESSION['logged_in'] == 1 && $login_type == "public"){ //logged in and on a public page- do nothing
  }
  else { //logged in and on a non-public page
    if($_SESSION['log_in_type']==$login_type){ //user login type and page login type match
    }
    else{ //user logging in to a non-authorized page
      redirect_to_base($login_type);
    }
  }
}


function isloggedin(){
  if(isset($_SESSION['logged_in'])){
    return $_SESSION['log_in_type'];
  }
  else{
    return false;
  }
}


function generate_header($type, $name){

  $index_page_name = "index.php";

  $header_before_title = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
				<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
				 <head>';
  $title = '  <title>' . $name . '</title>';
  $header_after_title = '  <link rel="stylesheet" href="';
  if($type != "public" ){
    $header_after_title .= '../';
  }
  $header_after_title .= 'stylesheet.php" type="text/css" />
			         <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
			        </head>';
  $header_after_title .=  ' <body>
				  <div id="container">
				   <div id="header">
				    <h1><a href="';
	
  if($type == "admin" || $type == "teller" || $type == "member")
    $index = "../" . $index_page_name;
  else if($type == "public")
    $index = $index_page_name;

  $header_after_title .= $index . '"><img src="';
  if($type != "public" ){
    $header_after_title .= '../';
  }
  $header_after_title .= 'fse bank.png" alt="Bank website" width="192" height="120" /></a></h1>
				   <div id="navigation">';
	
  if($type == "member" ){
    $navigation = '<ul>
 			 <li><a href="member.php?action=acctlist">Account Listing</a></li>
			  <li><a href="member.php?action=transfer">Transfers</a></li>
                          <li><a href="member.php?action=cuap">Change Password</a></li>
			  <li><a href="../contact_us.php">Contact us</a></li>
 			 <li><a href="../help.php">Help</a></li>
 			 <li><a href="../signoff.php">Sign off</a></li>
			</ul>
			</div>
			</div>';
  }
  else if($type == "admin" ){
    $navigation = '<ul>
 			 <li><a href="administrator_home.php?action=cua">Create User Account</a></li>
			  <li><a href="administrator_home.php?action=cuas">Change User Account Status</a></li>
			  <li><a href="administrator_home.php?action=respass">Reset User Account Password</a></li>
                          <li><a href="administrator_home.php?action=cuai">Change User Account Information</a></li>
 			 <li><a href="../signoff.php">Sign off</a></li>
			</ul>
			</div>
			</div>';
  }
	
  else if($type == "teller" ){
    $navigation = '<ul>
 			 <li><a href="teller.php?action=tdeposit">Teller Deposit</a></li>
			  <li><a href="teller.php?action=twithdrawal">Teller Withdrawal</a></li>
			  <li><a href="teller.php?action=ttransfer">Teller Transfer</a></li>
			 <li><a href="teller.php?action=cnba">Create New Bank Account</a></li>
			 <li><a href="teller.php?action=gad">Get account details of user</a></li>
 			 <li><a href="../signoff.php">Sign off</a></li>
			</ul>
			</div>
			</div>';
  }
	
  else{
    $navigation = '
			  <ul>
			    <li><a href="existing_customers.php">Existing Customers</a></li>
			    <li><a href="bank_info.php">Bank account plans and rates</a></li>
			    	 <li><a href="help.php">Help</a></li>
			    <li><a href="contact_us.php">Contact us</a></li>
			  </ul>
			</div>
 		     </div>';
  }
  $header = $header_before_title . $title . $header_after_title . $navigation;

  echo $header;	
}	
function connect_db(){
  global $connection; 
  $connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
  if (!$connection) {
    die("Database connection failed: " . mysql_error());
  }

  // 2. Select a database to use 
  $db_select = mysql_select_db(DB_NAME,$connection);
  if (!$db_select) {
    die("Database selection failed: " . mysql_error());
  }
}

function authenticate_user($username, $userpass){
  $username = mysql_real_escape_string($username);
  $userpass = mysql_real_escape_string($userpass);
  $authquery = "select count(*) as valid from User WHERE UserID = \"{$username}\" AND password = AES_ENCRYPT(\"{$userpass}\", 'my_secret_key_to_encrypt')";
  $result = mysql_query($authquery);
  confirm_query($result);
  $queryresult = mysql_fetch_array($result);
  if($queryresult['valid'] == 1)
    return true;
  else
    return false;
} 

function is_existing_user($username,$ssn,$email,$allargs=true){
  $username = mysql_real_escape_string($username);
  $ssn = mysql_real_escape_string($ssn);
  if($allargs)
    $existquery = "select count(*) as valid from User WHERE UserID = \"{$username}\" OR SSN = {$ssn} OR Email = \"{$email}\";";
  else
    $existquery = "select count(*) as valid from User WHERE UserID = \"{$username}\";";
  $result = mysql_query($existquery);
  confirm_query($result);
  $queryresult = mysql_fetch_array($result);

  if(intval($queryresult['valid']) >= 1){
    $string = $queryresult['valid'] . " " . $username . " " . $ssn . " " . $email;
    return $string;
  }
  else{
    return false;
  }
}

function get_user_type($username){
  $username = mysql_real_escape_string($username);
  $typequery = "select TypeID from User where UserID = \"{$username}\";";
  $result = mysql_query($typequery);
  confirm_query($result);
  $queryresult = mysql_fetch_array($result);
  return $queryresult["TypeID"];
}

function  create_user($userid,$userpass,$usertype, $userphone, $useradd, $useraddcity, $useraddstate, $useraddzip, $username, $userssn, $userdob, $useremail, $userbranch){
  $userid = mysql_real_escape_string($userid);
  $userpass = mysql_real_escape_string($userpass);

  $usertype = mysql_real_escape_string($usertype);
  $userphone = mysql_real_escape_string($userphone);
  $useradd = mysql_real_escape_string($useradd);
  $useraddcity = mysql_real_escape_string($useraddcity);
  $useraddstate = mysql_real_escape_string($useraddstate);
  $useraddzip = intval(mysql_real_escape_string($useraddzip));
  $username = mysql_real_escape_string($username);
  $userssn = intval(mysql_real_escape_string($userssn));
  $userdob = mysql_real_escape_string($userdob);
  $useremail = mysql_real_escape_string($useremail);
  $userbranch = mysql_real_escape_string($userbranch);

  $createuserquery = "INSERT INTO User VALUES(\"{$userid}\", AES_ENCRYPT(\"{$userpass}\", 'my_secret_key_to_encrypt'),\"{$usertype}\", \"{$userphone}\", \"{$useradd}\", \"{$useraddcity}\", \"{$useraddstate}\",{$useraddzip}, \"{$username}\", {$userssn}, \"{$userdob}\", \"{$useremail}\", \"{$userbranch}\")";

  $result = mysql_query($createuserquery);
  if ($result) {
    $message = "The user was successfully created.";
    return $message;
  } else {
    $message = "The user could not be created.";
    $message .= "<br />" . mysql_error();
    return $message;
  }
}

//Echoes failure or success messages depending on arguments in website url
function teller_argumenthandler(){
  if(isset($_GET['isblank'])){ //if fields were empty
    echo '<strong>Failure: All fields must be filled with valid data!</strong>';
  }

  if(isset($_GET['worry'])){
    echo "<strong>";
    switch($_GET['worry']){
    case -9:
      echo "Please give a valid entry in the User field";
      break;
    case -8:
      echo "Please give an amount higher than the minimum balance.";
      break;
    case -7:
      echo "The given user does not exist";
      break;
    case -6:
      echo "Transaction unsuccessful";
      break;
    case -5:
      echo "The deposit amount is not valid. Transaction canceled";   
      break;
    case -4:
      echo "The transfer amount is more than the transfer limit for the account!";   
      break;
    case -3:
      echo "Please give a vaild transfer amount!";      
      break;
    case -2:
      echo 'You have given an invalid account!';
      break;    
    case -1:
      echo  "This transaction would result in an overdraw.  Transaction canceled!";
      break;    
    case 0:
      echo "The destination and source accounts or the same! Transaction canceled";
      break; 
    case 1:
      echo "Transaction successful";
      break;
    case 2:
      echo "New bank account creation successful";
      break;    
    }
    echo "</strong>";
  }		
}

function admin_argumenthandler(){

  if(isset($_GET['stat'])){
    echo "<strong>";
    switch($_GET['stat']){
    case -9:
      echo "The user ssn is not valid";
      break;
    case -8:
      echo "The given password is incorrect";
      break;
    case -7:
      echo "The passwords do not match";
      break;
    case -6:
      echo "The account given does not exist.";
      break;
    case -5:
      echo "Please input a valid State";
      break;
    case -4:
      echo "Please input a valid email address";
      break;
    case -3:
      echo "This user does not exist in the system.";
      break;
    case -2:
      echo "This user already exists in the system in some form.  Check for existing userid, SSN, or email address."; 
      break;
    case -1:
      echo "Please fill out all the fields!";
      break;	
    case 1:
      echo "The User has been created.";
      break;
    case 2:
      echo "User information has been updated";
      break;
    case 3:
      echo "The account status has been successfully updated!";
      break;
    case 4:
      echo "The account password has been successfully updated!";
      break;

    }
    echo "</strong>";
  }		
}

function member_argumenthandler(){

  if(isset($_GET['arg'])){
    echo "<strong>";
    switch($_GET['arg']){
    case -7:
      echo "Please fill out all the fields!";
      break;
    case -6:
      echo "Invalid account given!";
      break;
    case -5:
      echo "Invalid transfer amount";
      break;
    case -4:
      echo "Transfer is more than transfer limit of account";
      break;
    case -3:
      echo "The given username/password is incorrect";
      break;
    case -2:
      echo "The passwords do not match";
      break;
    case -1:
      echo "This transaction would result in an overdraw.  Transaction canceled!";
      break;	
    case 0:
      echo "Source and destination accounts are same. Transaction canceled!";
      break;
    case 1:
      echo "The account password has been successfully updated!";
      break;
    case 2:
      echo "The transaction was successful";
      break;

    }
    echo "</strong>";
  }		
}

//returns 0- if 2 accounts are same
//returns -1 - if transaction would result in anopverdraw
//returns 1 - if successful 
function transfer($transamount,$sacc,$dacc)
{
  if($sacc == $dacc)
    return 0;
  else{
    //get transfer limit
    //get balance of sacc
    //get minbalance of sacc
    //check balance remaining in sacc after transaction
    //execute transaction
    $transferlimitquery = "select TransferLimit from AccountType where TypeID = (Select TypeID from Account where AccountNumber = {$sacc});";
    $transferlimitresult = mysql_query($transferlimitquery);
    confirm_query($transferlimitresult);
    $transferlimit = mysql_fetch_array($transferlimitresult);

    if($transamount > $transferlimit['TransferLimit']){
      return -4;
    }

    $saccbalancequery = "select Balance from Account where AccountNumber = {$sacc};";
    $saccbalanceresult = mysql_query($saccbalancequery);
    confirm_query($saccbalanceresult);
    $saccbalance = mysql_fetch_array($saccbalanceresult);

    $daccbalancequery = "select Balance from Account where AccountNumber = {$dacc};";
    $daccbalanceresult = mysql_query($daccbalancequery);
    confirm_query($daccbalanceresult);
    $daccbalance = mysql_fetch_array($daccbalanceresult);

    $saccminbalancequery = "select MinimumBalance from AccountType where TypeID = (Select TypeID from Account where Accountnumber = {$sacc});";
    $saccminbalanceresult = mysql_query($saccminbalancequery);
    confirm_query($saccminbalanceresult);
    $saccminbalance = mysql_fetch_array($saccminbalanceresult);
      
    $daccupdatedbalance = $daccbalance['Balance'] + $transamount;
    $saccupdatedbalance = $saccbalance['Balance'] - $transamount;
    if($saccupdatedbalance <= $saccminbalance['MinimumBalance']){
      return -1;
    }
    else{
      //subtract transammount from saccbalance and compare to sacc minimum balance
      update_account_attribute($dacc, "Balance", $daccupdatedbalance);
      update_account_attribute($sacc, "Balance", $saccupdatedbalance);     

      //get max transaction id
      $maxtransactionquery = "Select Max(TransID) as TransID from Transaction;";
      $maxtransactionresult = mysql_query($maxtransactionquery);
      confirm_query($maxtransactionresult);
      $maxtransaction = mysql_fetch_array($maxtransactionresult);

      $id1 = $maxtransaction['TransID'] + 1;
      $id2 = $maxtransaction['TransID'] + 2;
  
      new_transaction("Credit", $dacc, $transamount, $id1);  
      new_transaction("Debit", $sacc, $transamount, $id2);
      return 1;
    }
  }
}
function deposit($depositamount, $toaccount){
  //First check if the account exists
  if(!is_existing_account($toaccount))
    return -2;
    
  //Next credit the account by first getting the account balance, adding the new amount and then updating the balance
  //Getting the account query
  $accbalancequery = "select Balance from Account where AccountNumber = {$toaccount};";
  $accbalanceresult = mysql_query($accbalancequery);
  confirm_query($accbalanceresult);
  $accbalance = mysql_fetch_array($accbalanceresult);

  //Adding the new amount
  $newaccbalance = $accbalance['Balance'] + $depositamount;
  
  //Updating the balance
  update_account_attribute($toaccount, "Balance", $newaccbalance); 
  //Then create the transaction
  new_transaction("Credit", $toaccount, $depositamount);
  return 1;
}


function is_existing_account($accountnum){
  $accountnum = mysql_real_escape_string($accountnum);
  $existquery = "select count(*) as valid from Account WHERE AccountNumber = {$accountnum} ;";
  $result = mysql_query($existquery);
  confirm_query($result);
  $queryresult = mysql_fetch_array($result);

  if(intval($queryresult['valid']) >= 1){ //If there is atleast 1 account with that number
    return true;
  }
  else{
    return false;
  }
}

//returns -4- if withdrawal amount more than withdrawal limit
//returns -1 - if withdrawing the account makes the account below mi. balance
//returns 1 - if withdrawal would be fine
function is_valid_withdrawalamount($withdrawalamount, $fromaccount){
  $withdrawallimitquery = "select WithdrawalLimit from AccountType where TypeID = (Select TypeID from Account where AccountNumber = {$fromaccount});";
  $withdrawallimitresult = mysql_query($withdrawallimitquery);
  confirm_query($withdrawallimitresult);
  $withdrawallimit = mysql_fetch_array($withdrawallimitresult);

  if($withdrawalamount > $withdrawallimit['WithdrawalLimit']){ // If amount is more than withdrawal limit
    return -4;
  }

  //Get current balance
  $fromaccountbalancequery = "select Balance from Account where AccountNumber = {$fromaccount};";
  $fromaccountbalanceresult = mysql_query($fromaccountbalancequery);
  confirm_query($fromaccountbalanceresult);
  $fromaccountbalance = mysql_fetch_array($fromaccountbalanceresult);

  $accupdatedbalance = $fromaccountbalance['Balance'] - $withdrawalamount;

  //Check if applying withdrawal overdrafts the account
  $accminbalancequery = "select MinimumBalance from AccountType where TypeID = (Select TypeID from Account where Accountnumber = {$fromaccount});";
  $accminbalanceresult = mysql_query($accminbalancequery);
  confirm_query($accminbalanceresult);
  $accminbalance = mysql_fetch_array($accminbalanceresult);
    
  if($accupdatedbalance < $accminbalance['MinimumBalance']){ //If withdrawing the account makes the account below min. balance
    return -1;
  }
  else
    return 1;
}

function get_user_from_accountid($acc){
  if(!is_existing_account($acc))
    return false;
  
  //Then get user id
  $userquery = "Select UserID from Account where AccountNumber = $acc;";
  $userresult = mysql_query($userquery);
  confirm_query($userresult);
  $user = mysql_fetch_array($userresult);
  return $user;

}

//returns -4- if withdrawal amount more than withdrawal limit
//returns -1 - if withdrawing the account makes the account below mi. balance
//returns 1 - if withdrawal would be fine
function withdrawal($withdrawalamount, $fromaccount){
  if(is_valid_withdrawalamount($withdrawalamount, $fromaccount) != 1){ //If withdrawal    
    return is_valid_withdrawalamount($withdrawalamount, $fromaccount);
  }

  //First do the withdrawal by first getting the current account balance then updating it
   
  //Get current balance
  $fromaccountbalancequery = "select Balance from Account where AccountNumber = {$fromaccount};";
  $fromaccountbalanceresult = mysql_query($fromaccountbalancequery);
  confirm_query($fromaccountbalanceresult);
  $fromaccountbalance = mysql_fetch_array($fromaccountbalanceresult);
  
  $accupdatedbalance = $fromaccountbalance['Balance'] - $withdrawalamount;
  
  $accwithdrawquery = "UPDATE Account SET Balance = {$accupdatedbalance} WHERE AccountNumber = {$fromaccount};";
  update_account_attribute($fromaccount, "Balance", $accupdatedbalance);

  //Next, record this as a transaction  
  new_transaction("Debit", $fromaccount, $withdrawalamount);
  
  return 1;
}


function create_new_bank_account($acctid, $type, $obalance, $userid, $acctstatus="closed", $branchid="34"){
  $acctid = intval($acctid);
  $obalance = intval($obalance);
  $date = getdate();
  $year = $date["year"];
  $month = $date["mon"];
  $day = $date["mday"];
  $newacctquery = "INSERT INTO Account VALUES($acctid,\"{$type}\", \"{$year}-{$month}-{$day}\", $obalance, \"{$userid}\", \"{$acctstatus}\", \"{$branchid}\");";
  $newacctresult = mysql_query($newacctquery);
  confirm_query($newacctresult);

  //Now record the transaction  
  new_transaction("Credit", $acctid, $obalance);
}

//Note: This function does not check if given values are valid!
function new_transaction($transtype, $affectedacct, $transamt, $transid=-1){
  
  //First get max transaction id
  $maxtransactionquery = "Select Max(TransID) as TransID from Transaction;";
  $maxtransactionresult = mysql_query($maxtransactionquery);
  confirm_query($maxtransactionresult);
  $maxtransaction = mysql_fetch_array($maxtransactionresult);
  
  if(intval($transid) == -1)
    $id1 = $maxtransaction['TransID'] + 1;
  else
    $id1 = intval($transid);
 
  //Then get user id
  $user = get_user_from_accountid($affectedacct);
  $userid = $user['UserID'];

  $date = getdate();
  $year = $date["year"];
  $month = $date["mon"];
  $day = $date["mday"];
  //insert the transaction into the transaction tables, debit and credit
  $transactionquery = "INSERT INTO Transaction VALUES($id1,\"{$transtype}\",$affectedacct,$transamt,\"34\", \"{$year}-{$month}-{$day}\", \"$userid\");";
  $transactionresult = mysql_query($transactionquery);
  confirm_query($transactionresult);
}

function get_user_accounts($userid){
  $acctquery = "Select AccountNumber, TypeID, Balance, AccountStatus from Account where UserID = \"{$userid}\";";
  $acctresult = mysql_query($acctquery);
  confirm_query($acctresult);
  return $acctresult;
}

function update_account_attribute($account, $attribute, $value){
  $account = intval($account);
  if($attribute == "AccountNumber" || $attribute == "Balance") //If value should be passed as an int
    $accquery = "UPDATE Account SET {$attribute} = {$value} WHERE AccountNumber = {$account};";
  else{ //Else value should be passed as a string
        $accquery = "UPDATE Account SET {$attribute} = \"{$value}\" WHERE AccountNumber = {$account};";
  }
  $accqueryresult = mysql_query($accquery);
  confirm_query($accqueryresult);  
}

function minacctbalance($accttype){
  $minbalquery = "SELECT MinimumBalance FROM AccountType WHERE TypeID = \"{$accttype}\";";
  $result = mysql_query($minbalquery);
  confirm_query($result);
  $result2 = mysql_fetch_array($result);
  return $result2['MinimumBalance'];
}

function  change_user_info( $userid, $username, $useradd, $useraddcity, $useraddstate, $useraddzip, $userphone, $useremail){
  update_user_attribute($userid, "UserID", $userid);
  update_user_attribute($userid, "Name", $username);
  update_user_attribute($userid, "Address", $useradd);
  update_user_attribute($userid, "City", $useraddcity);
  update_user_attribute($userid, "State", $useraddstate);
  update_user_attribute($userid, "Zip", $useraddzip);
  update_user_attribute($userid, "PhoneNumber", $userphone);
  update_user_attribute($userid, "Email", $useremail);
  
}

function update_user_attribute($userid, $attribute, $value){
  $accquery = "UPDATE User SET {$attribute} = \"{$value}\" WHERE UserID = \"{$userid}\";";
  $accqueryresult = mysql_query($accquery);
  confirm_query($accqueryresult);  
}

function passwords_match($passone, $passtwo){
  if($passone == $passtwo)
    return true;
  else
    return false;
}

function change_password($pass, $userid){
  $pass = mysql_real_escape_string($pass);
  $passquery = "UPDATE User Set Password = AES_ENCRYPT(\"{$pass}\", 'my_secret_key_to_encrypt') WHERE UserID=\"{$userid}\"";
  $passresultquery = mysql_query($passquery);
  confirm_query($passresultquery);
}

function get_transactions_foraccount($acctnum){
  $gettrans = "SELECT * FROM Transaction WHERE AccountNumber = {$acctnum} ORDER BY TransID DESC";
  $gettransquery = mysql_query($gettrans);
  confirm_query($gettransquery);
  return $gettransquery;
}

?>
